<template>
  <page-wrap :header-props="headerProps">
    <div class="confirm-container">
      <div class="confirm-container-main">
        <div class="container-main-header">
          <div class="container-main-header-wrap">
            <div class="main-header-title">
              <div>桌号：</div>
              <div
                :class="[
                  'tableNumber',
                  tableNumber ? 'orange' : 'gray',
                  query.reserveCode ? null : 'into'
                ]"
                @click="onTableSelect"
              >
                {{ tableNumber ? tableNumber : '选择桌位' }}
              </div>
            </div>
            <div class="main-header-value">{{ tableType }}</div>
          </div>
        </div>
        <van-form
          input-align="right"
          class="container-main-form"
          @submit="onSubmit"
        >
        <!-- 赤红门店手机号、姓名、人数、到店时间、性别 无需必填 -->
          <van-cell-group inset :border="false">
            <van-field
              v-model="postForm.memberMobile"
              :required="isRequired"
              name="电话"
              label="电话"
              placeholder="请输入电话"
              autocomplete="off"
              type="digit"
              maxlength="11"
              @blur="findInfo"
            />
            <van-field
              v-model="postForm.memberName"
              :required="isRequired"
              name="姓名"
              class="required"
              label="姓名"
              placeholder="请输入姓名"
              autocomplete="off"
            />
            <van-field
              v-model="postForm.peopleNumber"
              name="人数"
              :required="isRequired"
              label="人数"
              placeholder="人数"
              autocomplete="off"
              type="digit"
              maxlength="2"
            />
            <van-field
              v-model="timeText"
              is-link
              readonly
              :required="isRequired"
              name="arrTime"
              label="到店时间"
              class="arrTime"
              placeholder="请选择时间"
              @click="onTime"
            />
            <van-field name="radio" label="性别" :required="isRequired">
              <template #input>
                <van-radio-group
                  v-model="postForm.sex"
                  direction="horizontal"
                  style="display: flex"
                  shape="dot"
                >
                  <van-radio name="011001" style="margin-right: 16px"
                    >先生</van-radio
                  >
                  <van-radio name="011002">女士</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field
              v-model="waiterText"
              is-link
              readonly
              name="waiter"
              label="服务员"
              placeholder="请选择"
              @click="waiterShow = true"
            />
            <van-field
              v-model="sourceText"
              is-link
              readonly
              name="from"
              label="来源"
              placeholder="请选择"
              @click="sourceShow = true"
            />
            <van-field
               v-model="pesronText"
              is-link
              readonly
              name="booker"
              label="订台人"
              placeholder="请选择"
              :style="{ opacity: postForm.sourceType == '104004' ? 1 : 0.4 }"
              @click="onBooker"
            />
            <van-field
              v-model="postForm.minConsume"
              name="低消"
              label="低消"
              placeholder="请输入低消"
              autocomplete="off"
            />
            <van-field
              v-model="specialText"
              is-link
              readonly
              name="ask"
              label="特殊要求"
              placeholder="请选择"
              @click="specialShow = true"
            />
            <van-field
              v-model="postForm.remark"
              type="textarea"
              name="备注"
              label="备注"
              placeholder="请输入备注"
              autocomplete="off"
              maxlength="100"
              show-word-limit
              autosize
              label-width="80"
              input-align="right"
            />
          </van-cell-group>
          <div class="kys-btn-fixed">
            <z-button-group>
            <z-button
              bold
              native-type="submit"
              top="20"
              :disabled="isDisabled"
              v-has-role="'waiter-reserve'"
              >{{ query.source == 'edit' ? '保存' : '预订' }}</z-button
            >
            <z-button
              bold
              @click.prevent="router.back()"
              top="10"
              :plain="true"
              style="margin-bottom: 10px"
              >取消</z-button
            >
          </z-button-group>
          </div>
        </van-form>
      </div>
    </div>
  </page-wrap>
  <z-picker-group
    v-model:show="timeShow"
    title="到店时间"
    :start-min-date="today"
    :start-max-date="nextWeek"
    @confirm="onConfirm($event, 'reserveTime')"
    :filter="filter"
  />
  <!-- <z-picker
    v-model:show="waiterShow"
    :columns="waiterColumns"
    title="服务员"
    @confirm="onConfirm($event, 'waiterUser')"
  /> -->
  <z-picker
    v-model:show="sourceShow"
    :columns="sourceColumns"
    title="来源"
    @confirm="onConfirm($event, 'sourceType')"
  />
  <!-- <z-picker
    v-model:show="bookerShow"
    :columns="bookerColumns"
    title="订台人"
    @confirm="onConfirm($event, 'maintainUser')"
  /> -->
  <z-picker
    v-model:show="specialShow"
    :columns="specialColumns"
    title="特殊要求"
    @confirm="onConfirm($event, 'specialRequireType')"
  />
  <TableSelect
    v-model:show="tableSelectShow"
    @close="onTableSelectClose"
    title="选择桌台"
    source="book"
    line="2"
  ></TableSelect>
  <van-popup v-model:show="Seletshow" round position="bottom" >
        <div class="select-continar">
          <div class="flex-box-sub">
              <div class="close" @click="Seletshow = false">取消</div>
              <div class="title">选择订台人</div>
              <div class="submit" @click="sumbitBooking">确定</div>
          </div>
          <z-search
            placeholder="请输入订台人"
            v-model="inputInfo"
            @query="Onsearch"
            @update:model-value="onUpdateVal"
          ></z-search>
          <div class="person-box">
            <div class="person-item" @click="selectItem(index,item)" v-for="(item,index) in fwyList" :key="index"  :class="{ selected: item.selected }">
                  {{ item.label }}
            </div>
            <z-empty type="data" v-if="!fwyList.length" />
          </div>
        </div>
  </van-popup>
      <van-popup v-model:show="waiterShow" round position="bottom" >
            <div class="select-continar">
              <div class="flex-box-sub">
                  <div class="close" @click="waiterShow = false">取消</div>
                  <div class="title">选择服务员</div>
                  <div class="submit" @click="sumbitPerson">确定</div>
              </div>
              <z-search
                placeholder="请输入"
                v-model="inputPersonInfo"
                @query="OnsearchPesron"
                @update:model-value="onUpdatePesronVal"
              ></z-search>
              <div class="person-box">
                <div class="person-item" @click="selectpesronItem(index,item)" v-for="(item,index) in waiterColumns" :key="index"  :class="{ selected: item.selected }">
                      {{ item.text }}
                </div>
                <z-empty type="data" v-if="!waiterColumns.length" />
              </div>
            </div>
      </van-popup>
</template>
<script setup>
import dayjs from 'dayjs'
import Api from '@/api'
import ls from '@/lib/ls'
import useConfigStore from '@/store/config'
import {
  transformArrayProps,
  validateMobile,
  validateName
} from '@/lib/util.js'
import { showToast } from 'vant'

import triangle from '@/assets/svg/confirm/v_confirm-triangle.svg'
import polygon from '@/assets/svg/confirm/v_polygon.svg'

const route = useRoute()
const router = useRouter()
const query = route.query
const configStore = useConfigStore()
const tableType = ref('--')
const tableNumber = ref(undefined)

// 赤红门店手机号、姓名、人数、到店时间、性别 无需必填
const isRequired = ref(true)
if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025' || ls.get('ORG_CODE') == '0021'){
  isRequired.value = false
}



const isDisabled = computed(() => {
  const { memberName, peopleNumber, memberMobile, reserveTime } = postForm
  if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025' || ls.get('ORG_CODE') == '0021'){
    return false
  }else{
    return !(
      unref(tableNumber) &&
      memberName &&
      peopleNumber
    )
  }
 
})

// 头部配置
const headerProps = computed(() => {
  let title = query.source == 'edit' ? '修改预订信息' : '预订'
  const r = {
    title
  }
  return r
})
// 根据手机号获取会员信息
const findInfo = ()=>{
  Api.Common.AppObjProcess.Do({
    functionName: 'GetMemberInfoByMobile',
    contentData: {mobile:postForm.memberMobile}
  })
  .then(res=>{
    console.log(res);
    postForm.memberName = res.result[0].memberName
  })
  .catch(error=>{
    // console.log(error);
  })
}


// 到店时间
const timeText = ref('')
const currentTime = ref(dayjs().format('YYYY-MM-DD')) // 当前时间
const reserveArrivalTime = ref('20:30')
let dateTimeString = ''
const GetBaseInfo = ()=>{
  Api.Common.AppObjProcess.Do({
      functionName: 'GetBaseConfigInfo',
      contentData: {orgCode:ls.get('ORG_CODE')}
  })
  .then(res=>{
    console.log(res);
    reserveArrivalTime.value = res.reserveArrivalTime
    dateTimeString = `${currentTime.value} ${reserveArrivalTime.value}`;
    timeText.value = dateTimeString
    postForm.reserveTime = dateTimeString
  })
}
GetBaseInfo() // 获取门店配置信息
console.log(configStore);


// 提交数据
const postForm = reactive({
  reserveCode: '',
  roomCode: '',
  memberName: '',
  peopleNumber: 2,
  memberMobile: '',
  reserveTime: '',
  sex: '011002',
  waiterUser: '',
  sourceType: '',
  maintainUser: '',
  specialRequireType: '',
  remark: '',
  minConsume: ''
})

const Submitflag = ref(false)
// 提交预订
const onSubmit = () => {
  postForm.maintainUser = pesronCode.value
  // if (!validateMobile(postForm.memberMobile)) return
  if (!validateName(postForm.memberName)) return
  if(Submitflag.value) {
    return
  }
  Submitflag.value = true
  Api.Common.AppObjProcess.Do({
    functionName: 'reserveAdd',
    contentData: postForm
  })
    .then(res => {
      if (query.source == 'open') {
        showToast('预订成功')
        router.replace('/open')
      }
      if (query.source == 'edit') {
        showToast('保存成功')
        router.back()
      } else {
        showToast('预订成功')
        router.back()
      }
      Submitflag.value = false
    })
    .catch(err => {
      console.log('err')
      Submitflag.value = false
    })
}

// 选择桌台
const onTableSelect = () => {
  if (query.reserveCode) return
  tableSelectShow.value = true
}
const tableSelectShow = ref(false)
const onTableSelectClose = (type, args) => {
  tableSelectShow.value = false
  if (type == 'back') return
  const { roomName, roomCode, typeCode, typeName, minConsume } = args
  if (roomName) {
    tableNumber.value = roomName
    postForm.roomCode = roomCode
    postForm.minConsume = minConsume
    tableType.value = typeName
  }
}



const timeShow = ref(false)
const today = dayjs().toDate() // 今天
const nextWeek = dayjs().add(1, 'week').toDate() // 一周后
const filter = (type, options) => {
  const nowHour = dayjs().hour()
  const nowMin = dayjs().minute()
  if (type === 'hour') {
    return options
      .filter(v => v.value >= nowHour)
      .filter(v => v.value <= 6 || v.value >= 18)
  }
  if (type === 'minute') {
    if (nowHour <= 6 || nowHour >= 18) {
      return options.filter(v => v.value >= nowMin)
    }
  }
  return options
}

// 服务员
const waiterText = ref('')
const waiterShow = ref(false)
// 来源
const sourceText = ref('')
const sourceShow = ref(false)
// 订台人
const bookerText = ref('')
const bookerShow = ref(false)
// 特殊要求
const specialText = ref('')
const specialShow = ref(false)

// 选项组
const waiterColumns = ref([])
const sourceColumns = ref([])
const bookerColumns = ref([])
const specialColumns = ref([])

// 弹窗确定按钮
const onConfirm = function (ev, type) {
  const opt = ev.selectedOptions ? ev.selectedOptions[0] : null
  switch (type) {
    case 'reserveTime':
      // timeTabs.value = [dayjs().format('YYYY-MM-DD') ,ev[1].selectedValues.join(':')]
      timeText.value = `${ev[0].selectedValues.join(
        '-'
      )} ${ev[1].selectedValues.join(':')}`
      postForm.reserveTime = unref(timeText) + ':00'
      timeShow.value = false
      break
    case 'waiterUser':
      waiterText.value = opt.text
      postForm.waiterUser = opt.value
      waiterShow.value = false
      if (!opt.value) {
        waiterText.value = ''
      }
      break
    case 'sourceType':
      sourceText.value = opt.text
      postForm.sourceType = opt.value
      sourceShow.value = false
      if (!opt.value) {
        sourceText.value = ''
      }
      break
    case 'maintainUser':
      bookerText.value = opt.text
      postForm.maintainUser = opt.value
      bookerShow.value = false
      if (!opt.value) {
        bookerText.value = ''
      }
      break
    case 'specialRequireType':
      specialText.value = opt.text
      postForm.specialRequireType = opt.value
      specialShow.value = false
      if (!opt.value) {
        specialText.value = ''
      }
      break
  }
}

// 点击时间
const onTime = function () {
  timeShow.value = true
}

// ----------------------------------订台人操作 ----------------------------------
const Seletshow = ref(false) //订台人弹窗状态
const fwyList = ref([])  //订台人列表
const inputInfo = ref('')  //搜索输入的值
const pesronText = ref('') //订台人名字
const pesronCode = ref('') //订台人code
// 获取订台人
const getWaiteretOrgGroup = ()=> {
  Api.Common.AppObjProcess.Do({
            functionName: 'GetOrgGroup',
            contentData: {"key":inputInfo.value}
          }).then(res => {
            fwyList.value = res.result
            console.log(res,'查询订台人列表')
          })
}

getWaiteretOrgGroup()

const selectItem = (index,v) => {
   // 取消所有项的选中状态
   fwyList.value.forEach(item => item.selected = false);
  // 选中当前点击的项
  fwyList.value[index].selected = true;
  pesronText.value = v.label
  pesronCode.value = v.value
};

// -------------------------------------------------------搜索---------------------------------------------------------------------
const Onsearch = () => {
  getWaiteretOrgGroup()
}

const searchTimer = ref(null)
const onUpdateVal = val => {
  clearTimeout(unref(searchTimer))
  searchTimer.value = setTimeout(() => {
    getWaiteretOrgGroup()
  }, 500)
}
//确定订台人
const sumbitBooking = ()=> {
       if(pesronText.value == "") {
           showToast('请选择订台人')
       } else {
         Seletshow.value = false
       }
}


// 点击订台人
const onBooker = function () {
  if (postForm.sourceType == '104004') {
    // bookerShow.value = true
    Seletshow.value = true
  }
}

//----------------------------------服务员操作 statrt ----------------------------------
const inputPersonInfo = ref('')
const tempText = ref('')
const tempUser = ref('')
const OnsearchPesron = ()=> {
  if (inputPersonInfo.value.trim() === "") {
    waiterColumns.value = [...originalWaiterColumns.value];
  } else {
    // 否则进行搜索，过滤数据
    waiterColumns.value = waiterColumns.value.filter(item =>
      item.text.toLowerCase().includes(inputPersonInfo.value.toLowerCase())
    );
  }
}
const onUpdatePesronVal = ()=> {
  clearTimeout(unref(searchTimer))
  searchTimer.value = setTimeout(() => {
    OnsearchPesron();
  }, 500)
}
const selectpesronItem = (index,v) => {
   // 取消所有项的选中状态
   waiterColumns.value.forEach(item => item.selected = false);
  // 选中当前点击的项
  waiterColumns.value[index].selected = true;
  tempText.value = v.text
  tempUser.value = v.value
};

const sumbitPerson = ()=> {
  const hasSelected = waiterColumns.value.some(item => item.selected);
  if (!hasSelected) {
    showToast('请选择服务员');
    return
  }
  waiterText.value = tempText.value
  postForm.waiterUser = tempUser.value
  waiterShow.value = false;
}

//----------------------------------服务员操作 end ----------------------------------

const originalWaiterColumns = ref([]) //保留服务员副本数据

// 监听来源
watch(
  () => postForm.sourceType,
  (nVal, oVal) => {
    if (nVal !== '104004') {
      bookerText.value = ''
      postForm.maintainUser = ''
    }
  }
)

// 初始化
const onInit = async function () {
  const { reserveCode, source } = query
  const transA = [
    ['userName', 'text'],
    ['userCode', 'value']
  ]
  const transB = [
    ['name', 'text'],
    ['code', 'value']
  ]
  // 获取订台人列表
  Api.Common.AppObjProcess.Do({
    functionName: 'getCustomerManageList',
    contentData: ''
  }).then(res => {
    bookerColumns.value = transformArrayProps(res.result, transA)
    Array.prototype.push.apply(bookerColumns.value, [{ text: '无', value: '' }])
  })
  // 获取来源列表
  sourceColumns.value = transformArrayProps(configStore.sourceList, transB)
  Array.prototype.push.apply(sourceColumns.value, [{ text: '无', value: '' }])
  // 获取特殊要求
  specialColumns.value = transformArrayProps(configStore.specialList, transB)
  Array.prototype.push.apply(specialColumns.value, [{ text: '无', value: '' }])
  // 获取服务员列表
  const getWaiter = await Api.Common.AppObjProcess.Do({
    functionName: 'getWaiterList',
    contentData: ''
  })
  waiterColumns.value = transformArrayProps(getWaiter.result, transA)
  Array.prototype.push.apply(waiterColumns.value, [{ text: '无', value: '' }])
  originalWaiterColumns.value = waiterColumns.value

  // 开台页预订
  if (source == 'open') {
    const { roomName, typeCode, typeName, minConsume, roomCode } = query
    tableNumber.value = roomName
    tableType.value = typeName
    postForm.minConsume = minConsume
    postForm.roomCode = roomCode
  }

  // 编辑预订
  if (reserveCode && source == 'edit') {
    Api.Common.AppObjProcess.Do({
      functionName: 'getReserveInfo',
      contentData: reserveCode
    }).then(res => {
      const resp = res.result[0]
      const {
        roomName,
        roomCode,
        roomTypeName,
        memberName,
        peopleNumber,
        memberMobile,
        reserveTime,
        sex,
        waiterUserCode,
        sourceTypeCode,
        maintainUserCode,
        maintainUserName,
        specialRequireTypeCode,
        specialRequireTypeName,
        minConsume,
        remark
      } = resp

      tableNumber.value = roomName
      tableType.value = roomTypeName
      timeText.value = dayjs(reserveTime).format('YYYY-MM-DD HH:mm')
      waiterText.value = waiterUserCode
        ? unref(waiterColumns).find(v => v.value == waiterUserCode).text
        : ''
      bookerText.value = maintainUserName
      sourceText.value = sourceTypeCode
        ? unref(sourceColumns).find(v => v.value == sourceTypeCode).text
        : ''
      specialText.value = specialRequireTypeName

      postForm.minConsume = minConsume
      postForm.reserveCode = reserveCode
      postForm.roomCode = roomCode
      postForm.memberName = memberName
      postForm.peopleNumber = peopleNumber
      postForm.memberMobile = memberMobile
      postForm.reserveTime = unref(timeText) + ':00'
      postForm.sex = sex
      postForm.waiterUser = waiterUserCode
      postForm.sourceType = sourceTypeCode
      postForm.maintainUser = maintainUserCode
      postForm.specialRequireType = specialRequireTypeCode
      postForm.remark = remark
    })
  } else {
    sourceText.value = '营销'
    postForm.sourceType = '104004'
  }
}
onInit()
</script>
<style scoped lang="scss">
.confirm-container {
  padding: 10px 12px 0px 12px;
  //  overflow-y: hidden;
  overflow-y: auto;
  .confirm-container-main {
    // background: #28282e;
    height: 75%;
    border-radius: 8px;
    padding: 0 4px 180px 4px;

    .container-main-header {
      background-color: #28282e;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
      padding: 0 4px;

      &-wrap {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-family: PingFang SC;
        font-weight: bold;
        padding: 16px 20px;
        border-bottom: 1px solid #383840;
      }

      .main-header-title {
        flex-basis: 50%;
        display: flex;
        // padding: 22px 0 0 20px;
        font-size: 18px;
        color: #ffffff;
        line-height: 18px;

        .tableNumber {
          color: #ffaa00;
          position: relative;
          padding-right: 14px;
          cursor: pointer;

          &.orange {
            color: #ffaa00;
          }

          &.gray {
            color: #999999;
            font-weight: 500;
          }

          &.into:after {
            content: '';
            position: absolute;
            right: 0;
            top: 4px;
            width: 6px;
            height: 11px;
            background-image: url('@/assets/svg/common/v_triangle_right_white.svg');
            background-repeat: no-repeat;
            background-size: 100% 100%;
          }
        }
      }

      .main-header-value {
        padding: 6px;
        // margin: 18px 20px 18px 0;
        font-size: 13px;
        background: #3c3933;
        border-radius: 4px;
        color: #ffaa00;
        line-height: 13px;
      }
    }

    .custom-content-main {
      .custom-content-item {
        padding: 18px 0 18px 0;
        font-size: 16px;
        color: #fefefe;
        font-family: PingFang SC;
        font-weight: 500;
        text-align: center;
        line-height: 16px;
        border-bottom: 1px solid #505059;
      }

      .custom-content-item:active {
        color: #ffaa00;
      }

      .custom-content-cancle {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 16px;
        text-align: center;
        padding: 18px 0 18px 0;
      }
    }

    :deep(.van-field__label--required:before) {
      position: absolute;
      left: 52px;
      top: 15px;
    }

    :deep(.arrTime .van-field__label--required:before) {
      left: 85px;
    }
  }

  .container-main-form {
    :deep(.van-field) {
      background-color: #28282e;
      border: none;
      padding: 17px 20px;
      align-items: center;
    }

    :deep(.van-field__label) {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #cccccc;
      line-height: 16px;
    }

    :deep(.van-cell-group) {
      background: #28282e;
      margin: 0;
      border-top-left-radius: 0;
      border-top-right-radius: 0;
    }

    // :deep(.van-cell-group--inset) {
    //     background: #28282e;
    //     margin: 0;
    // }

    :deep(::-webkit-input-placeholder) {
      //   默认值字体颜色
      color: #999999;
    }

    :deep(.van-cell:after) {
      border-bottom: 1px solid #383840;
    }

    :deep(.van-field__control) {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff !important;
      line-height: 16px;
    }

    :deep(.van-field__control--min-height) {
      line-height: 20px;
    }

    :deep(.van-radio__label) {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 16px;
      margin-left: 6px;
    }

    :deep(.van-radio--horizontal) {
      margin-right: 0px;
    }

    :deep(.van-radio__icon--checked.van-radio__icon--dot
        .van-radio__icon--dot__icon) {
      background: #ffaa00;
    }

    :deep(.van-radio__icon--checked.van-radio__icon--dot) {
      border-color: #ffaa00;
    }

    :deep(.van-cell__right-icon) {
      //   font-size: 0;
      margin-left: 2px;
      color: rgba(0, 0, 0, 0);
      /* 将字体颜色设置为完全透明 */
      background-image: url('@/assets/svg/confirm/v_confirm-triangle.svg');
      background-repeat: no-repeat;
      background-position: center center;
      background-size: 10px 6px;
    }

    :deep(.van-popup--bottom) {
      background: #45454d;
      border-radius: 24px 24px 0px 0px;
      padding: 0 12px 0 12px;
    }
  }
}
.select-continar {
  min-height: 300px;
  background: #45454d;
  .flex-box-sub {
    padding: 0 24px;
    display: flex;
    justify-content: space-between;
    height: 50px;
    line-height: 50px;
    .close {
      color: #999999;
       font-size: 16px;
    }
    .title {
      font-size: 20px;
      text-align: center;
      color: #fff;
    }
    .submit {
      font-size: 16px;
      color: #ea9d05;
    }
  }
  .person-box {
       height: 400px;
       padding-top: 20px;
       padding-bottom: 70px;
       overflow-y: auto;
       .person-item {
        text-align: center;
           font-size: 14px;
           color: #fff;
           margin-bottom: 25px;
       }
  }
  .person-item.selected {
      color:#ea9d05; /* 选中项的文字颜色 */
    }
}

.kys-btn-fixed {
  position: fixed;
  bottom: 0;
  width:91%;
}
</style>
